package com.leyou.filter;

import com.leyou.common.auth.domain.Payload;
import com.leyou.common.auth.domain.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.AuthContants;
import com.leyou.common.exception.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JsonUtils;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import java.security.cert.TrustAnchor;
import java.util.concurrent.ForkJoinWorkerThread;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
@Slf4j
@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})
public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProp;
    @Autowired
    private FilterProperties filterProp;
    /**
     * 过滤时机
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER+1;
    }

    /**
     * 过滤开关
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 处理逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //判断当前请求是否在白名单，如果在白名单，直接return null,结束此方法
        Boolean isWhite = handlerWhite(filterProp, request.getRequestURI());
        if (isWhite) {
            return null;
        }
        //得到token需要cookie名
        String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());
        //解析token是否合法
        Payload<UserInfo> payload=null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            log.error("用户权限不足");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }
        //得到token中的role信息放入请求头，传递给其他微服务
        String role = payload.getUserInfo().getRole();
        ctx.addZuulRequestHeader("USER_ROLE",role);
        ctx.addZuulRequestHeader(AuthContants.USER_ID,payload.getUserInfo().getId().toString());
        log.info("用户名:"+AuthContants.USER_ID+"用户id："+payload.getUserInfo().getId().toString());
        return null;
    }

    /**
     * 返回值为true表示白名单，false表示黑名单
     * @param filterProp
     * @param requestURI
     */
    private Boolean handlerWhite(FilterProperties filterProp, String requestURI) {
        for (String allowPath : filterProp.getAllowPaths()) {
            if (requestURI.startsWith(allowPath)) {
                return true;
            }
        }
        return false;
    }
}
